import { loginApi,getUserInfo } from "@/api/user/user";
import { LoginParm, LoginResult } from "@/api/user/UserModel";
import { Result } from "@/utils/request";
import { ActionContext } from "vuex";
import { RootState } from "../index";
import { setTokens, setUserId, setExpireTime } from '@/utils/auth';
export type UserState = {
  token: string,
  userId: string,
  permissions:Array<string>
}
export const state: UserState = {
  token: '',
  userId: '',
  permissions:[]
}
export const mutations = {
  setToken: (state: UserState, token: string) => {
    state.token = token
  },
  setUserId: (state: UserState, userId: string) => {
    state.userId = userId
  },
  setPermissions:(state:UserState,permissions:string[])=>{
    state.permissions = permissions
  }
}
export const actions = {
  login({ commit }: ActionContext<UserState, RootState>, loginParm: LoginParm) {
    return new Promise<Result>((resolve, reject) => {
      loginApi(loginParm).then(res => {
        if (res.data.code === 200) {
          commit('setToken', res.data.token)
          commit('setUserId', res.data.id)
          setTokens(res.data.token)
          setUserId(res.data.id)
          setExpireTime(res.data.expireTime)
        }
        resolve(res)
      }).catch(error=>{
        reject(error)
      })
    })
  },
  getInfo({commit}:ActionContext<UserState,RootState>){
    return new Promise((resolve,reject)=>{
      getUserInfo().then((res)=>{
       commit('setPermissions',res.data.roles)
       resolve(res.data)
      }).catch((error)=>{
        reject(new Error(error))
      })
    })
  }
}
export const getters={
  getToken(state:UserState){
    return state.token
  },
  getPermissions(state:UserState){
    return state.permissions
  }
}
export default{
  namespaced:true,
  state,
  mutations,
  actions,
  getters
}